﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Maxleaf.EDI.Domain;
using Maxleaf.EDI.Domain.EDI;

namespace Maxleaf.EDI.Core.Handlers.QueryHandlers
{
    public class GetUserDBsQueryHandler : IQueryHandler<Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsParameters, Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsResult>
    {
        private readonly IUnitOfWorkProvider unitOfWorkProvider;
        private readonly IRepository<DBDesc> dbRepository;
        private readonly IRepository<User_DB> userRepository;

        public GetUserDBsQueryHandler(
            IRepository<DBDesc> dbRepository,
            IRepository<User_DB> userRepository,
            IUnitOfWorkProvider unitOfWorkProvider)
        {
            this.dbRepository = dbRepository;
            this.userRepository = userRepository;
            this.unitOfWorkProvider = unitOfWorkProvider;
        }

        public Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsResult Handle(Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsParameters parameters)
        {
            using (var unitOfWork = this.unitOfWorkProvider.GetEDIUnitOfWork())
            {
                var user = this.userRepository.GetSingleOrDefault(unitOfWork,u=>u.UserName==parameters.UserName);
                if (user == null  || string.IsNullOrEmpty(user.DBID))
                {
                    return new Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsResult { DBs = new List<Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsResult.DB>() };
                }

                var dbids = user.DBID.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries);
                var dbs = this.dbRepository.GetAll(unitOfWork).Where(o => o.FDeleted == 0 && dbids.Contains(o.DBID));

                return new Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsResult() { DBs = dbs.Select(o => new Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsResult.DB { FInterId=o.Finterid, DBId=o.DBID, DBName=o.DBName}).ToList() };
            }
        }
    }
}
